package com.i2works.smartluolong.manageapi.shiro;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.i2works.smartluolong.utils.base.ShiroConstants;
import com.i2works.smartluolong.utils.common.HmacUtil;
import com.i2works.smartluolong.utils.shiro.filter.StatelessToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 自定义api shiro权限realm
 *
 * @author Liu Yutao koal@vip.qq.com
 * @date 2018/5/15 11:34
 */
public class SmartManageAPIRealm extends AuthorizingRealm {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean supports(AuthenticationToken token) {
        //仅支持StatelessToken类型的Token
        return token instanceof StatelessToken;
    }

    /**
     * 权限认证《获取授权URL连接》
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        JSONObject userParams = (JSONObject) principals.getPrimaryPrincipal();
        return new SimpleAuthorizationInfo();
    }

    /**
     * 授权认证《获取权限角色》
     * 通过账号等账号信息，获取数据库账号信息，写入SimpleAuthenticationInfo发送到前台进行对比
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        StatelessToken statelessToken = (StatelessToken) token;
        //获取用户ID
        Integer userId = statelessToken.getUserId();
        //获取用户名
        String userName = statelessToken.getUserName();
        //获取密钥key
        String key = HmacUtil.getKey(userName);
        //根据客户端参数，生成服务器的摘要
        Map<String, Object> params = Maps.newLinkedHashMap();
        params.put(ShiroConstants.APP_USERID, userId);
        params.put(ShiroConstants.APP_USERNAME, userName);
        params.put(ShiroConstants.APP_TIMESTAMP, statelessToken.getDate());
        String serverDigest = HmacUtil.digest(key, params);
        logger.error("服务端的摘要：" + serverDigest);
        //传递用户信息
        JSONObject userParams = new JSONObject();
        userParams.put(ShiroConstants.APP_USERID, userId);
        userParams.put(ShiroConstants.APP_USERNAME, userName);
        return new SimpleAuthenticationInfo(userParams, serverDigest, getName());
    }

}
